<template>
  <div class="index">
    <van-nav-bar class="top" :fixed="true">
      <template #title>
        <h4>首页</h4>
      </template>
      <template #right>
        <van-icon
          @click="$router.push('/search')"
          name="search"
          size="18"
          class="icon"
        />
      </template>
    </van-nav-bar>
    <div class="navbar" v-if="userChannelList && userChannelList[0]">
      <div @click="popupBtn">
        <van-icon name="bars" class="fiexd" />
      </div>
      <van-tabs v-model="active" @click="onClick">
        <van-tab
          :name="index"
          :title="item.name"
          v-for="(item, index) in userChannelList"
          :key="item.id"
        >
        </van-tab>
      </van-tabs>

      <van-pull-refresh
        head-height="100"
        v-model="refreshing"
        @refresh="onRefresh"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="不给你看了"
          @load="onLoad"
        >
          <article
            v-show="articleList && item"
            v-for="(item, index) in articleList"
            :key="index"
          >
            <div class="title" @click="$router.push('/detail/' + item.art_id)">
              {{ item.title }}
            </div>
            <div class="img" v-if="item && item.cover && item.cover.images">
              <img
                v-for="(value, key) in item.cover.images"
                :key="key"
                :src="value"
                :alt="item.aut_name"
                :title="item.aut_name"
              />
            </div>
            <div class="footer">
              <div class="author">{{ item.aut_name }}</div>
              <div class="comment">{{ item.comm_count }}评论</div>
              <div class="time">{{ item.pubdate | hmfilter }}</div>
              <div
                @click="delArticle(index, item.art_id, item.aut_id)"
                class="del"
                cross
              >
                <van-icon class="editicon" name="cross" />
              </div>
            </div>
          </article>
        </van-list>
      </van-pull-refresh>
    </div>
    <!-- list refresh -->
    <van-popup
      v-if="userChannelList && userChannelList[0]"
      class="tanchu"
      v-model="show"
      position="bottom"
      :style="{ height: '70%' }"
    >
      <div class="onetitle">
        <h4>我的频道</h4>
        <div class="edit" @click="editOrOk">
          {{ edit ? '完成' : '编辑' }}
        </div>
      </div>
      <div class="span">
        <span
          class="item"
          v-for="(item, index) in userChannelList"
          :key="index"
          @click="see(index)"
          :class="{ myactive: active === index }"
          >{{ item.name }}
          <van-icon
            v-if="edit && index !== 0"
            @click.stop="shiftChan(item.id)"
            name="cross"
          />
        </span>
      </div>
      <div class="title">
        <h4>频道推荐</h4>
      </div>
      <div class="span" :class="{ disablePoint: !edit }">
        <span
          @click="addChannel(item.id, item.name, index)"
          class="item"
          v-for="(item, index) in list"
          :key="index"
          >{{ item.name }}</span
        >
      </div>
    </van-popup>

    <van-dialog class="dialog" v-model="dialogShow" show-cancel-button>
      <div @click="notInt(artId)"><van-icon name="bill-o" />不感兴趣</div>
      <div class="center" @click="mydialogShow = true">
        <van-icon name="warn-o" /><span>反馈垃圾内容</span>
        <van-icon name="arrow" />
      </div>
      <div @click="blackAuthor"><van-icon name="delete-o" />拉黑作者</div>
    </van-dialog>
    <van-dialog
      class="mydialog"
      v-model="mydialogShow"
      :showConfirmButton="false"
      :closeOnClickOverlay="true"
    >
      <div @click="mydialogShow = false">
        <van-icon name="arrow-left" />
      </div>
      <div
        @click="reports(art_id, index)"
        v-for="(item, index) in type"
        :key="index"
      >
        {{ item }}
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import {
  channelsApi, // 所有频道
  articlesApi, // 获取文章
  userInfoApi, // 用户信息
  userChannelsApi, // 用户频道
  setUserChannel, // 设置用户频道
  reportsApi, // 举报文章
  dislikeApi, // 不喜欢文章
  blacklistApi // 拉黑用户
} from '@/api/loginApi.js'
export default {
  name: 'index',
  data () {
    return {
      loading: false,
      finished: false,
      refreshing: false,
      type: [
        '其他问题',
        '标题夸张',
        '低俗色情',
        '错别字多',
        '旧闻重复',
        '广软文',
        '内容不实',
        '涉嫌违法犯罪',
        '侵权'
      ],
      currentChannelId: '',
      author_id: '',
      art_id: '',
      artId: '',
      editValue: '编辑',
      edit: false,
      show: false,
      active: 0,
      list: [], // 所有频道的数组,
      id: '',
      time: '',
      per_page: '',
      articleList: [],
      userChannelList: [],
      articleId: '',
      dialogShow: false,
      mydialogShow: false
    }
  },
  created () {
    // 获取用户频道信息
    this.getUserChannels()
    // 获取所有频道信息
    this.getAllPin()
    // 获取用户信息
    this.getuser()
  },
  activated () {
    // 当在别的路由切换回来时，判断是否有scrolltop，有就跳回到此位置
    if (this.$route.meta.scrollTop) {
      window.scrollTo(0, this.$route.meta.scrollTop)
    }
  },
  methods: {
    // 编辑与完成按钮
    async editOrOk () {
      this.edit = !this.edit
      if (!this.edit) {
        // 完成
        const channels = this.userChannelList.map((item, index) => {
          return { id: item.id, name: item.name, seq: index + 1 }
        })
        channels.splice(0, 1)
        await setUserChannel(channels)
        this.show = false
      }
    },
    // list refresh start
    async onLoad () {
      if (this.refreshing) {
        this.articleList = []
        this.refreshing = false
      }
      this.time = new Date().getTime()
      const res = await articlesApi(
        this.userChannelList[this.active].id,
        this.time,
        1
      )
      this.articleList.push(...res.data.results)
      this.loading = false
      // if (this.articleList.length > 40) {
      //   this.finished = true
      // }
      if (!res.data.results[1]) {
        this.finished = true
      }
    },
    onRefresh () {
      // 清空列表数据
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    // list refresh end
    // 获取用户频道信息
    async getUserChannels () {
      const res = await userChannelsApi()
      if (res.message === 'OK') {
        this.userChannelList = res.data.channels
        this.currentChannelId = this.userChannelList[this.active].id
      }
    },
    // 弹出我的频道
    popupBtn () {
      this.show = true
      // 静默刷新
      this.edit = true
      this.$nextTick(() => {
        this.edit = false
      })
    },
    // 用户数据
    ...mapMutations(['getUserInfo']),
    async getuser () {
      const res = await userInfoApi()
      this.getUserInfo(res.data)
    },
    // 获得所有频道的api axios请求
    async getAllPin () {
      const res = await channelsApi()
      if (res.message === 'OK') {
        this.list = res.data.channels
        const channel = []
        setTimeout(() => {
          this.userChannelList.forEach(item => {
            return channel.push(item.name)
          })
          // 防止list里的数据和userChannelList里的数据重复
          this.list = this.list.filter(function (item) {
            return channel.indexOf(item.name) < 0
          })
          this.id = this.list[this.active].id
          this.getArticle(this.id)
        }, 1000)
      }
    },
    // 获得频道id 相对应的文章
    async getArticle (id) {
      this.time = new Date().getTime()
      const res = await articlesApi(id, this.time, 1)
      this.articleList.push(...res.data.results)
    },
    // 当切换频道的时候，发送新的频道最新资讯
    onClick (name, title) {
      this.currentChannelId = this.userChannelList[name].id
      this.refreshing = true
      this.onLoad()
    },

    // 当文章被点击关闭的时候，刷新articleList
    delArticle (index, id, aut) {
      this.dialogShow = true
      this.artId = index
      this.art_id = id
      this.author_id = aut
    },
    // 当用户点击不感兴趣的时候关闭文章
    async notInt (index) {
      // 删除文章列表本地
      this.$toast.loading('提交中...')
      this.articleList.splice(index, 1)
      // 发送网络请求，不喜欢文章
      const res = await dislikeApi(this.art_id)
      if (res.message === 'OK') {
        this.$toast.success({
          message: '为您减少此类信息的推荐',
          duration: 1000
        })
        this.dialogShow = false
      }
    },
    // 当用户点击举报类型的时候，进行举报
    async reports (artId, index) {
      this.$toast.loading('提交中...')
      const res = await reportsApi(artId, index)
      if (res.message === 'OK') {
        this.$toast.success({
          message: '举报成功',
          duration: 1000
        })
        this.mydialogShow = false
        this.dialogShow = false
      }
    },
    // 当用户拉黑作者的时候
    async blackAuthor () {
      const res = await blacklistApi(this.author_id)
      if (res.message === 'OK') {
        this.$toast.success({
          message: '拉黑成功',
          duration: 1000
        })
        this.dialogShow = false
      }
    },
    // 我的频道点击看看index
    see (index) {
      this.active = index
      // 重新加载不同id的文章列表
      this.refreshing = true
      this.onLoad()
    },
    // 添加频道
    addChannel (id, name, index) {
      this.userChannelList.push({ id, name })
      this.list.splice(index, 1)
    },
    // 删除频道
    async shiftChan (id) {
      const count = this.userChannelList.findIndex(item => {
        return item.id === id
      })
      // 删除被选中的数据
      const newDate = this.userChannelList.splice(count, 1)
      // 将删除的数据添加到推荐频道列表
      this.list.push(newDate[0])
    }
  },
  adddd () {
    window.console.log('你管我')
  }
}
</script>

<style lang="less" scoped>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.disablePoint {
  pointer-events: none; // 禁用点击事件
}
.dialog {
  div {
    padding: 5px 0px 5px 15px;
    border-bottom: 1px solid #cecece;
    &:nth-last-child(2) {
      display: flex;
      span {
        flex: 1;
      }
    }
    i.van-icon {
      margin-right: 10px;
      vertical-align: text-top;
    }
  }
}
.mydialog {
  div {
    padding: 5px 0px 5px 15px;
    border-bottom: 1px solid #cecece;
    i.van-icon {
      margin-right: 10px;
      vertical-align: text-top;
    }
  }
}
.myactive {
  color: #ff1c14 !important;
}
.index {
  margin-top: 100px;
  margin-bottom: 50px;
}
.top {
  background: #3296fa;
  h4 {
    color: white;
    font-size: 20px;
  }

  /deep/ .icon {
    color: white;
    font-size: 134px;
    font-weight: 700;
  }
}
.navbar {
  .fiexd {
    position: fixed;
    top: 50px;
    right: 0;
    height: 100%;
    z-index: 2;
    background: #ffc0cb;
  }
  /deep/ .van-tabs__wrap {
    position: fixed;
    top: 1.22667rem;
    left: 0;
    width: 90%;
    z-index: 999;
  }
  /deep/ i.fiexd.van-icon.van-icon-bars {
    margin-top: -4px;
    height: 40px;
    width: 35px;
    text-align: center;
    line-height: 40px;
  }
}
article {
  padding: 0 15px;
  margin-bottom: 10px;
  margin-top: 5px;
  .title {
    font-size: 15px;
    margin: 5px 0;
    font-weight: 700;
  }
  .img {
    img {
      width: 30%;
      height: 70px;
      margin: 3px 5px;
      font-size: 10px;
    }
  }
  .footer {
    display: flex;
    font-size: 12px;
    .comment {
      margin: 0 10px;
    }
    .time {
      flex: 1;
    }
  }
}
.tanchu {
  padding: 10px 0;

  .onetitle {
    display: flex;
    h4 {
      flex: 1;
      padding: 0 15px;
      color: #454445;
      font-size: 18px;
      font-weight: 400;
      margin: 5px 0;
    }
    .edit {
      font-size: 16px;
      // padding: 10px 15px;
      border-radius: 15px;
      text-align: center;
      margin-right: 10px;
      width: 60px;
      height: 30px;
      line-height: 30px;
      border: 1px solid #ee0a24;
      color: #ee0a24;
    }
  }
  h4 {
    padding: 0 15px;
    color: #454445;
    font-size: 18px;
    font-weight: 400;
    margin: 5px 0;
  }
  .span {
    text-align: center;
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    margin-top: 10px;
    .item {
      position: relative;
      width: 25%;
      padding: 10px;
      border: 1px solid #f5f5f7;
      font-size: 14px;
      margin: 0px 0px -1px -1px;
      /deep/ i.van-icon.van-icon-cross {
        border-radius: 50%;
        background: #646566;
        color: #fafafa;
        position: absolute;
        top: 0;
        right: 0;
        padding: 1px;
      }
    }
  }
}
</style>
